<?php
/**
 * Copyright (c) [2019] [吴跃忠]
 * [selibra] is licensed under the Mulan PSL v1.
 * You can use this software according to the terms and conditions of the Mulan PSL v1.
 * You may obtain a copy of Mulan PSL v1 at:
 * http://license.coscl.org.cn/MulanPSL
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v1 for more details.
 */

namespace Zooclient\storage;

use Selibra\Config\Config;
use Selibra\Table\TableFactory;
use Swoole\Table;
use Zooclient\exception\WriteException;

class SwooleTableZooStorage implements ZooDataStorageInterface
{

    /**
     * TableKey
     * @var string
     */
    public static string $tableKey = 'zooclient-data-storage-table';

    /**
     * value 的最大长度
     * @var int
     */
    public static int $valueSize = 100000;

    /**
     * table 的最大行度
     * @var int
     */
    public static int $tableSize = 500;

    /**
     * 系统配置
     */
    public function configure()
    {
        $config = Config::get('zooclient.storage');
        if (!empty($config['table_size'])) {
            self::$tableSize = $config['table_size'];
        }
        if (!empty($config['value_size'])) {
            self::$valueSize = $config['value_size'];
        }
        // 配置Table
        $table = new Table(self::$tableSize, 1);
        $table->column('value', Table::TYPE_STRING, self::$valueSize);
        $table->create();
        TableFactory::addTable(self::$tableKey, $table);
    }


    /**
     * 提供读取的
     * @param string $key
     * @return string|false
     */
    public function read(string $key): string|false
    {
        return TableFactory::getTable(self::$tableKey)->get($key, 'value');
    }


    /**
     * @param string $key
     * @param string $value
     * @return bool
     * @throws WriteException
     */
    public function write(string $key, string $value): bool
    {
        if (strlen($value) > self::$valueSize) {
            throw new WriteException('$value is to long');
        }
        TableFactory::getTable(self::$tableKey)->set($key, [
            'value' => $value
        ]);
        return true;
    }
}
